const FETCH_USER = 'FETCH_USER';
import * as Immutable from "immutable";
const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
import {GET_USER_INFO_REQUEST, GET_USER_INFO_SUCCESS, GET_USER_INFO_FAILURE} from "../actions/mainAction";
type stateType = Immutable.Map<string, any>;
//action is to tell reducer how to deal with data!!

const defaultState = Immutable.Map({
  userInfo: null,
});

const getUserInfoSuccess: any = (state: stateType, action:any) => {
  let newState = state;
  const userInfo = action.result[0];
  newState = newState.set("userInfo", userInfo);
  return newState;
};

const getUserInfoFail: any = (state: stateType, action:any) => {
  const newState = state;
  action.errorText = {
    error: "未授权",
    errorTitle: "未授权",
  };
  return newState;
};

export default function user(state = defaultState, action: any) {
  switch (action.type) {
    case FETCH_USER_FULFILLED:
      return {
        ...state,
        [action.payload.login]: action.payload
      }; 
    case GET_USER_INFO_SUCCESS:
      return getUserInfoSuccess(state, action);
    case GET_USER_INFO_FAILURE:
      return getUserInfoFail(state, action);
    default:
      return state;
  }
}